package com.appspot.moviesessions;

import android.content.Intent;
import android.view.View;
import android.view.ViewGroup.OnHierarchyChangeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;

public class MovieSessionPresenter {

	private MovieSessionView view;
	private LoaderFactory loaderFactory;
	private ContentUri contentUri;

	public MovieSessionPresenter(MovieSessionView movieSessionView,
			LoaderFactory loaderFactory, ContentUri contentUri) {
		this.view = movieSessionView;
		this.loaderFactory = loaderFactory;
		this.contentUri = contentUri;
	}

	public void onStart() {
		Intent intent = view.getIntent();
		String dataString = intent.getDataString();
		final long selectedMovieId = contentUri.parseId(dataString);
		Loader movieSpinnerLoader = loaderFactory.movieSpinnerLoader();
		view.getSupportLoaderManager().initLoader(0x03, null,
				movieSpinnerLoader);
		Spinner movieSpinner = view.getMovieSpinner();
		movieSpinner.setAdapter(movieSpinnerLoader);
		movieSpinner
				.setOnHierarchyChangeListener(new SetInitialSelectedMovieHierarchyChangeListener(
						selectedMovieId));
		movieSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View child,
					int position, long movieId) {
				Spinner locationSpinner = view.getLocationSpinner();
				Loader locationLoader = loaderFactory
						.locationSpinnerLoader(movieId);
				locationSpinner.setAdapter(locationLoader);
				view.getSupportLoaderManager().destroyLoader(0x04);
				view.getSupportLoaderManager().initLoader(0x04, null,
						locationLoader);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}

		});

	}

	public static class SetInitialSelectedMovieHierarchyChangeListener
			implements OnHierarchyChangeListener {

		private long selectedMovieId;

		public SetInitialSelectedMovieHierarchyChangeListener(
				long selectedMovieId) {
			super();
			this.selectedMovieId = selectedMovieId;
		}

		@Override
		public void onChildViewRemoved(View parent, View child) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onChildViewAdded(View parent, View child) {
			Spinner spinner = (Spinner) parent;
			SpinnerAdapter adapter = spinner.getAdapter();
			for (int x = 0; x < adapter.getCount(); x++) {
				long itemId = adapter.getItemId(x);
				if (itemId == selectedMovieId) {
					spinner.setSelection(x, true);
					spinner.setOnHierarchyChangeListener(null);
					break;
				}
			}
		}
	}
}
